<template>
  <div class="components-container">
    <div>
      <el-row>
        <el-col :span="3">
          <div style="font-size: 20px; font-weight: 500; line-height: 37px">
            请输入标题:
          </div>
        </el-col>
        <el-col :span="10">
          <el-input
            maxlength="50"
            placeholder="请在这里输入标题"
            show-word-limit
            v-model="post.title"
          ></el-input>
        </el-col>
      </el-row>
    </div>
    <el-divider></el-divider>
    <div class="editPost">
      <quill-editor
        ref="myQuillEditor"
        v-model="post.content"
        :options="editorOption"
        @change="onEditorChange"
      />
      <!-- @change="onEditorChange($event)" -->
    </div>
    <el-upload
      v-show="false"
      class="avatar-uploader1"
      :action="loadUrl"
      :show-file-list="false"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
    <div>
      <el-button style="margin-left: 350px" type="success" @click="publish"
        >发&nbsp;表</el-button
      >
      <el-popconfirm
        title="辛苦了这么久真的要重置吗？"
        style="margin-left: 30px"
        @confirm="reset"
      >
        <el-button type="warning" slot="reference">重&nbsp;置</el-button>
      </el-popconfirm>
    </div>
  </div>
</template>

<script>
import { publishPost, getOne } from "../../api/postMg";

import Quill from "quill";
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { ImageDrop } from "quill-image-drop-module"; // 图片拖动组件引用
import ImageResize from "quill-image-resize-module"; // 图片缩放组件引用
Quill.register("modules/imageDrop", ImageDrop); // 注册
Quill.register("modules/imageResize", ImageResize); // 注册

const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗，斜体，下划线，删除线
  ["blockquote", "code-block"], //引用，代码块
  [{ header: 1 }, { header: 2 }], // 几级标题
  [{ list: "ordered" }, { list: "bullet" }], // 有序列表，无序列表
  [{ script: "sub" }, { script: "super" }], // 下角标，上角标
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  // [{ 'direction': 'rtl' }],                         // 文字输入方向
  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 颜色选择
  [{ font: [] }], // 字体
  [{ align: [] }], // 居中
  // ["clean"], // 清除样式,
  ["image"], // 上传图片、上传视频
];

export default {
  name: "EditPost",
  props: {
    postId: {
      type: Number,
      require: false,
    },
  },
  components: {
    quillEditor,
  },
  data() {
    return {
      //富文本上传的图片
      loadUrl:
        "http://127.0.0.1:8088/loadImg/post?userId=" +
        localStorage.getItem("userId"),
      // 帖子的表单
      post: {
        // id:1,
        // // 帖子的标题
        // title:"啊啊啊啊啊啊啊啊啊啊",
        // // 富文本编辑器默认内容
        // content:'sfasfasfa',
        // userId:"202403030001",
        // postingTime:"2023-03-03 12:01:01",
        // delFlag:0
      },
      // 富文本编辑器配置
      editorOption: {
        placeholder: "请在这里输入内容",
        theme: "snow", //主题 snow：有工具栏的；bubble：只有文本域的
        history: {
          delay: 1000,
          maxStack: 50,
          userOnly: false,
        },
        modules: {
          imageDrop: true, //图片拖拽
          imageResize: {
            //放大缩小
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
          toolbar: {
            container: toolbarOptions, //工具栏
            handlers: {
              image: function (value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector(".avatar-uploader1 input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
    };
  },
  methods: {
    async getDetails() {
      await getOne(this.postId).then(res=>{
        if(res.data.code == 200){
          this.post = res.data.data
        }else{
          this.$message.error(res.data.code+"::"+res.data.msg)
        }
      })
    },
    publish() {
      // 点击发表
      if (this.post.title.length < 3) {
        this.$message.error("标题太短了哦");
        return;
      }
      if (this.post.content.length < 20) {
        this.$message.error("内容长度小于20了哦");
        return;
      }
      publishPost(localStorage.getItem("userId"), this.post).then((res) => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
          this.post = {};
        } else {
          this.$message.error(res.data.code + "::" + this.data.msg);
        }
      });
    },
    beforeUpload(file) {
      const isJPEG = file.type === "image/jpeg";
      const isJPG = file.type === "image/jpg";
      const isPNG = file.type === "image/png";
      // const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPEG && !isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (file.size > 10 * 1024 * 1024) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      return true;
    },
    handleSuccess(res, file, fileList) {
      console.log(file, fileList);
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill;
      // 如果上传成功
      if (res.code === 200) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.info为服务器返回的图片地址
        quill.insertEmbed(length, "image", res.data);
        // 调整光标到最后
        quill.setSelection(length + 1);
        // this.$forceupdate();
      } else {
        this.$message.error(res.msg);
      }
      // loading动画消失
      this.quillUpdateImg = false;
    },
    reset() {
      this.post.title = "";
      this.post.content = "";
    },
    //富文本内容改变事件
    onEditorChange(e) {
      console.log(e.html);
      // console.log(this.post.content);
      // this.content = e.html;
    },
  },
  mounted() {
    // console.log('postId1',this.postId);
    if (this.postId != null && this.postId != "") {
      //就去查单个帖子，因为是编辑
      this.getDetails()
    }
  },
  destroyed() {
    this.$emit("deletePostId");
    // console.log('postId2',this.postId);
  },
};
</script>
<style scpped>
.ql-container {
  font-size: 16px;
  height: 300px;
}
.el-input__inner {
  background-color: rgba(255, 255, 255, 0.5); /* 白色背景，50% 透明度 */
}
</style>
